#include "pictureitem.h"

#include <QtDeclarative/qdeclarative.h>
#include <QFile>
#include <QDebug>
#include <QUrl>
#include <QString>
#include <QImage>
#include <QPainter>
#include <QVariantMap>
#include <QTimer>
#include <QDir>
#include <QDirIterator>
#include <QApplication>
#include <QDateTime>
#include <QDocumentGallery>
#include <QDesktopServices>
#include <QSystemInfo>
#include <QSystemStorageInfo>
#include "drawthread.h"



PictureItem::PictureItem(QDeclarativeItem *parent):
        QDeclarativeItem(parent),
        m_background(Qt::transparent),
    m_backgroundOld(Qt::transparent),
    m_thread(NULL)
{
    // By default, QDeclarativeItem does not draw anything. If you subclass
    // QDeclarativeItem to create a visual item, you will need to uncomment the
    // following line:

    // setFlag(ItemHasNoContents, false);    
    m_resolutions[QVGA] = QStringList() << QString::number(320) << QString::number(240);
    m_resolutions[VGA] = QStringList() << QString::number(640) << QString::number(480);
    m_resolutions[SVGA] = QStringList() << QString::number(800) << QString::number(600);
    m_resolutions[XGA] = QStringList() << QString::number(1024) << QString::number(768);
    m_resolutions[WXGA] = QStringList() << QString::number(1280) << QString::number(768);
}

PictureItem::~PictureItem()
{
    qDebug() << __PRETTY_FUNCTION__;
    QDirIterator di(EMPTYIMAGE_PATH,QStringList() << "*.jpg",QDir::NoDotAndDotDot|QDir::Files);
    while(di.hasNext()){
        QString name = di.next();
        qDebug() << "removing: " << name;
    }
}

void PictureItem::createImage(ImageSizes imageSize, QVariantList imageList, QString fileName, QColor background, int margin, int aspectRatio)
{
    qDebug() << __PRETTY_FUNCTION__ << " imageSize: " << imageSize << " filename: " << fileName << " background: " << background << " margin: " << margin;
    m_imageSize = imageSize;
    m_imageList = imageList;
    m_fileName = fileName;
    m_background = background;
    m_margin = margin;    
    m_aspect = aspectRatio;

    if(m_thread)
        delete m_thread;
    m_thread = new DrawThread(m_picturesHome,m_resolutions);
    connect(m_thread,SIGNAL(finished()),this,SLOT(drawFinished()));

    m_thread->createImage(m_imageType,m_imageSize,m_imageList,m_fileName,m_background,m_backgroundOld,m_margin,m_aspect);
}

QStringList PictureItem::resolutionAsString(ImageSizes imageSize)
{
    qDebug() << __PRETTY_FUNCTION__ << " imageSize: " << imageSize;
    return m_resolutions[imageSize];
}

QString PictureItem::imageSizeAsString(ImageSizes imageSize)
{
    QString ret;
    switch(imageSize){
    case QVGA:{
        ret = "QVGA";
    }break;
    case VGA:{
        ret = "VGA";
    }break;
    case SVGA:{
        ret = "SVGA";
    }break;
    case XGA:{
        ret = "XGA";
    }break;
    case WXGA:{
        ret = "WXGA";
    }break;
    default:break;
    }
    return ret;
}

QString PictureItem::imageSizeWithResolutionAsString(ImageSizes imageSize)
{
    qDebug() << __PRETTY_FUNCTION__;
    QString ret;
    switch(imageSize){
    case QVGA:{
        ret = "QVGA "+m_resolutions[QVGA].at(0)+"x"+m_resolutions[QVGA].at(1);
    }break;
    case VGA:{
        ret = "VGA "+m_resolutions[VGA].at(0)+"x"+m_resolutions[VGA].at(1);
    }break;
    case SVGA:{
        ret = "SVGA "+m_resolutions[SVGA].at(0)+"x"+m_resolutions[SVGA].at(1);
    }break;
    case XGA:{
        ret = "XGA "+m_resolutions[XGA].at(0)+"x"+m_resolutions[XGA].at(1);
    }break;
    case WXGA:{
        ret = "WXGA "+m_resolutions[WXGA].at(0)+"x"+m_resolutions[WXGA].at(1);
    }break;
    default:break;
    }
    qDebug() << "return: " << ret;
    return ret;
}

void PictureItem::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
}

void PictureItem::setBackground(QColor backgroundColor)
{
    qDebug() << __PRETTY_FUNCTION__;
    m_backgroundOld = m_background;
    m_background = backgroundColor;
}

QUrl PictureItem::emptyImage()
{
    qDebug() << __PRETTY_FUNCTION__;
    bool back = false;
    bool type = false;
    if(m_background == m_backgroundOld)
        back = true;
    if(m_imageType == m_imageTypeOld)
        type = true;

    qDebug() << "back: " << back;
    qDebug() << "type: " << type;
    if(m_background != m_backgroundOld || m_imageType != m_imageTypeOld || m_emptyName.isEmpty()){
        QDir tempdir;
        if(tempdir.mkpath(EMPTYIMAGE_PATH))
            qDebug() << "dir created";
        else
            qDebug() << "dir not created";

        if(QFile::remove(m_emptyName))
            qDebug() << "remove success";
        else
            qDebug() << "remove failed";

        m_emptyName = EMPTYIMAGE_PATH+QString::number(qrand())+".jpg";
        qDebug() << "emptyname: " << m_emptyName;
        QImage* img = new QImage(QSize(1280,768),IMAGE_FORMAT);
        QPainter* combiner = new QPainter(img);
        combiner->fillRect(QRect(0,0,img->width(),img->height()),m_background);

        bool save = img->save(m_emptyName);

        if(img->isNull())
            qDebug() << "empty image is null";
        if(!save)
            qDebug() << "cannot create empty image";

        m_backgroundOld = m_background;
        delete combiner;
        delete img;
    }
    return QUrl::fromLocalFile(m_emptyName);
}

QString PictureItem::freeFilename()
{
    qDebug() << __PRETTY_FUNCTION__;
    QString fn;
    int count=0;
    int subcount = 0;
    QString date = QDate::currentDate().toString("ddMMyyyy");
    date = APP_NAME_SHORT+date;

    QDirIterator di(m_picturesHome,QStringList() << "*.jpg",QDir::Files);
    while(di.hasNext()){
        QString name = di.next();
        QFileInfo fi(name);
        name = fi.baseName();
        if(QString::compare(date,name,Qt::CaseInsensitive)==0)
            count++;

        QStringList list = name.split('_');
        if(list.count()>1){
            if(QString::compare(date,list.at(0),Qt::CaseInsensitive)==0){
                if(subcount<list.at(1).toInt())
                    subcount = list.at(1).toInt();
            }
        }
    }

    if(subcount && !count)
        count = 1;
    count+=subcount;

    if(count)
        fn = date+"_"+QString::number(count)+".jpg";
    else
        fn = date+".jpg";

    return fn;
}

void PictureItem::drawFinished()
{
    qDebug() << __PRETTY_FUNCTION__;
    bool success = m_thread->success();
    bool stopped = m_thread->stopRequested();
    m_currentImage = QUrl::fromLocalFile(m_thread->filename());
    delete m_thread;
    m_thread = NULL;
    if(!stopped){
        emit imageFinished(success);
    }else{
        m_currentImage.clear();
        emit canceled();
    }
}

void PictureItem::cancelDrawer()
{
    qDebug() << __PRETTY_FUNCTION__;
    if(m_thread){
        if(m_thread->isRunning()){            
            m_thread->stopWorking();
        }
    }
}

PictureItem::DriveStorage PictureItem::storage()
{
    qDebug() << __PRETTY_FUNCTION__;
    return m_storage;
}

void PictureItem::setStorage(DriveStorage storage)
{
    qDebug() << __PRETTY_FUNCTION__ << " " << storage;
    QtMobility::QSystemStorageInfo sysInfo;
    QStringList drives = sysInfo.logicalDrives();
    qDebug() << "drives: " <<drives;
    switch(storage){
    case StorageInternal:{
        m_picturesHome = QString::null;
        QString path(QDesktopServices::storageLocation(QDesktopServices::PicturesLocation));

        if(drives.contains("e",Qt::CaseInsensitive)){
            int ind = drives.indexOf(QRegExp("e",Qt::CaseInsensitive));
            qDebug() << "ind: " << ind;
            if(ind > -1){
                QString id = drives[ind];
                qDebug() << "drive: " << id << " type: " << sysInfo.typeForDrive(id);
                if(QtMobility::QSystemStorageInfo::InternalDrive == sysInfo.typeForDrive(id) ||
                        QtMobility::QSystemStorageInfo::RemovableDrive == sysInfo.typeForDrive(id)){
                    if(sysInfo.availableDiskSpace(id)>0){
                        m_picturesHome = id;
                        QStringList splitted = path.split('/',QString::SkipEmptyParts);
                        path = ":/"+splitted.last();
                    }
                }
            }
        }
        if(m_picturesHome.isEmpty()){
            m_picturesHome="C";
            path = path.mid(1);
        }
        m_storage = storage;
        m_picturesHome = m_picturesHome.append(path);
    }break;
    case StorageRemovable:{
        QString newHome;
        foreach(QString drive, drives){
            qDebug() << "drive: " << drive << " type: " << sysInfo.typeForDrive(drive);
            if(QtMobility::QSystemStorageInfo::RemovableDrive == sysInfo.typeForDrive(drive)){
                newHome = drive;
                m_storage = storage;
            }
        }
        if(newHome.isEmpty()){
            m_storage = StorageError;
        }else{
            m_picturesHome = newHome;
            QString tmp(QDesktopServices::storageLocation(QDesktopServices::PicturesLocation));
            QStringList splitted = tmp.split('/',QString::SkipEmptyParts);
            m_picturesHome = m_picturesHome.append(":/"+splitted.last());
        }
    }break;
    case Gallery:{
        m_picturesHome = QDesktopServices::storageLocation(QDesktopServices::PicturesLocation);
        m_storage = storage;
    }break;
    default:
        m_storage = StorageError;
        break;
    }

    if(!m_picturesHome.isEmpty() && !m_picturesHome.endsWith('/'))
        m_picturesHome = m_picturesHome.append("/");
    qDebug() << "Save path: " << m_picturesHome;
    qDebug() << "Storage state: " << m_storage;
    emit storageChanged(m_storage);
}
